import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:yt_devops/components/network_image_load/load_image.dart';
import 'package:yt_devops/model/picture_upload_setting.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/site/site_setting/site_setting_base_info/widgets/phone_preview.dart';
import 'package:yt_devops/pages/site/site_setting/site_setting_base_info/widgets/picture_header_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/common/common_services.dart';
import 'package:yt_devops/styles/styles.dart';
import 'my_gesture_detector.dart';
import 'log_utils.dart';

class SelectPhotoWidget extends StatefulWidget {
  final Function(List<String>)? imageUrlCallBack; //增加或者减少图片的回调
  final List<String> imagesUrlList; //需要显示图片列表
  final bool isCanDelete; //是否显示删除图标
  final int maxCount;
  final Color backgroundColor;

  String titleString;
  final double titleFontSize;
  String decString;
  num photoWidth;

  final EdgeInsets padding;
  SelectPhotoWidget(this.imagesUrlList, this.isCanDelete, this.maxCount,
      this.imageUrlCallBack,
      {this.titleString = '',
      this.decString = '',
      this.photoWidth = 76,
      this.titleFontSize = 16,
      this.backgroundColor = Colors.white,
      this.padding = const EdgeInsets.only(left: 16),
      Key? key})
      : super(key: key);

  @override
  State<SelectPhotoWidget> createState() => _SelectPhotoWidgetState();
}

class _SelectPhotoWidgetState extends State<SelectPhotoWidget> {
  final GlobalKey _gridWrapKey = GlobalKey();

  int gridCrossCount = 3;

  @override
  initState() {
    super.initState();
    if (widget.titleString.isEmpty) {
      widget.titleString = ResKey.siteBaseInfoSitePhotos.tr;
    }
    if (widget.decString.isEmpty) {
      widget.decString = ResKey.siteBaseInfoLimitPictures3.tr;
    }
    num maxWidth = (ScreenUtil().screenWidth - 16 * 2 - 10 * 2) / 3.0;

    if (maxWidth < widget.photoWidth) {
      //传入图片宽度超过了最大限制 那么就用最大宽度
      widget.photoWidth = maxWidth;
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      var w = _gridWrapKey.currentContext?.size?.width;
      // 计算出大概的列数
      var count = (w! / (widget.photoWidth.w)).floor();
      // 再加上crossAxisSpacing计算出实际的列数
      while (count * widget.photoWidth.w + (count - 1) * 10 > w) {
        count--;
      }

      setState(() {
        gridCrossCount = count == 0 ? gridCrossCount : count;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    Log.d('imagesUrlList==${widget.imagesUrlList}');

    return Container(
      color: widget.backgroundColor,
      padding: widget.padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          PictureHeaderWidget(
            titleString: widget.titleString,
            decString: widget.decString,
            titleFontSize: widget.titleFontSize,
          ),
          _imageListWidget(context, widget.maxCount),
        ],
      ),
    );
  }

  Widget? _addImageWidget(BuildContext context,
      {num containerW = 76,
      num containerH = 76,
      // String decString = ResKey.pickImg.tr,
      bool isLogo = false}) {
    return widget.isCanDelete
        ? GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              _askUserForImageSource(context, isLogo: isLogo);
            },
            child: Container(
              clipBehavior: Clip.hardEdge, //超出部分，可裁剪
              decoration: const BoxDecoration(
                  color: Colour.backgroundColor,
                  borderRadius: BorderRadius.all(Radius.circular(6))),
              height: ScreenUtil().setWidth(containerW),
              width: ScreenUtil().setWidth(containerW),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    alignment: Alignment.center,
                    child: const Icon(
                      Icons.add,
                      color: Colour.lightTextColor,
                    ),
                  ),
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(left: 6.w),
                    child: Text(
                      ResKey.pickImg.tr,
                      textAlign: TextAlign.center,
                      style: ytTextStyle(
                          color: Colour.lightTextColor, fontSize: 12.sp),
                    ),
                  )
                ],
              ),
            ),
          )
        : null;
  }

  _imageWidget(
    String imageString, {
    bool isShowClose = false,
    Function? deleteCallBack,
    Function? imageClickCallBack,
    num containerW = 76,
    num containerH = 76,
  }) {
    return SizedBox(
      // color: Colour.green,
      // height: ScreenUtil().setWidth(containerW),
      width: ScreenUtil().setWidth(containerW),
      child: Stack(
        children: [
          GestureDetector(
            onTap: () {
              if (imageClickCallBack != null) {
                imageClickCallBack();
              }
            },
            child: Container(
              clipBehavior: Clip.hardEdge, //超出部分，可裁剪
              decoration: const BoxDecoration(
                  color: Colour.white,
                  borderRadius: BorderRadius.all(Radius.circular(6))),
              child: LoadImage(
                imageString,
                height: ScreenUtil().setWidth(containerW),
                width: ScreenUtil().setWidth(containerW),
                fit: BoxFit.cover,
              ),
            ),
          ),
          Visibility(
            visible: isShowClose,
            child: Positioned(
              top: 0,
              right: 0,
              child: MyGestureDetector(
                onTap: () {
                  if (deleteCallBack != null) {
                    deleteCallBack();
                  }
                },
                child: Container(
                  padding: const EdgeInsets.all(3),
                  // color: Colors.green,
                  child: Icon(
                    Icons.close,
                    color: Colors.white,
                    size: 14.sp,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  ///站点照片视图
  _imageListWidget(BuildContext context, int maxCount) {
    List<Widget> list = [];

    for (int i = 0; i < widget.imagesUrlList.length; i++) {
      var imageWidget = _imageWidget(
        widget.imagesUrlList[i],
        isShowClose: widget.isCanDelete,
        containerW: widget.photoWidth,
        containerH: widget.photoWidth,
        deleteCallBack: () {
          widget.imagesUrlList.removeAt(i);
          if (widget.imageUrlCallBack != null) {
            widget.imageUrlCallBack!(widget.imagesUrlList);
          }
          setState(() {});
        },
        imageClickCallBack: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              fullscreenDialog: true, //是否从底部弹出
              builder: (_) => PhotoPreview(
                widget.imagesUrlList,
                defaultImage: i,
              ),
            ),
          );
        },
        // isShowClose: controller.isEnableEdit,
      );

      list.add(imageWidget);
    }
    if (widget.imagesUrlList.length < maxCount) {
      var uploadWidget = _addImageWidget(context,
          containerH: widget.photoWidth, containerW: widget.photoWidth);
      if (uploadWidget != null) {
        list.add(uploadWidget);
      }
    }

    return Container(
      key: _gridWrapKey,
      width: gridCrossCount * widget.photoWidth.w + (gridCrossCount - 1) * 10,
      padding: const EdgeInsets.only(bottom: 16),
      child: GridView(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: gridCrossCount,
          mainAxisSpacing: 15,
          crossAxisSpacing: 10,
        ),
        children: list,
      ),
    );
  }

  Future<ImageSource?> _askUserForImageSource(BuildContext context,
      {bool isLogo = false}) async {
    return await showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
        cancelButton: CupertinoActionSheetAction(
          isDestructiveAction: true,
          child: Text(
            ResKey.cancel.tr,
            style: const TextStyle(color: Colour.primaryColor),
          ),
          onPressed: () {
            Navigator.pop(context, null);
          },
        ),
        actions: <Widget>[
          CupertinoActionSheetAction(
            child: Text(
              ResKey.camera.tr,
              style: const TextStyle(color: Colour.warningTextColor),
            ),
            onPressed: () async {
              _handleImage(context, ImageSource.camera);
            },
          ),
          CupertinoActionSheetAction(
            child: Text(ResKey.gallery.tr),
            onPressed: () {
              _handleImage(context, ImageSource.gallery);
            },
          ),
        ],
      ),
    );
  }

  _handleImage(BuildContext context, ImageSource source) async {
    Log.d('_handleImage==');
    Navigator.pop(context, source);
    final ImagePicker imagePicker = ImagePicker();

    final image = await imagePicker.pickImage(source: source, imageQuality: 50);
    if (image == null) {
      return;
    }
    var cropSettings = const ImageManipulationSettings(
        enableCropping: true, compressQuality: 50);


    final CroppedFile? croppedFile = await ImageCropper().cropImage(
      sourcePath: image.path,
      // aspectRatio: cropSettings.aspectRatio,
      maxWidth: cropSettings.maxWidth,
      maxHeight: cropSettings.maxHeight,
      uiSettings: [
        IOSUiSettings(
            doneButtonTitle: ResKey.confirm.tr,
            cancelButtonTitle: ResKey.cancel.tr),
        AndroidUiSettings(
            toolbarTitle: '', hideBottomControls: true), //没办法 ，只能干掉工具栏支持国际化版本
      ],
    );
    if (croppedFile != null) {
      var file = File(croppedFile.path);
      uploadImage(file);
    }
  }

  ///上传单张图片
  void uploadImage(File? image) async {
    if (image != null) {
      showLoading(toast: ResKey.loading.tr);
      var result = await CommonServices().upload(image);
      dismissLoading();
      if (result != null && result['url'] != null) {
        widget.imagesUrlList.add(result['url'].toString());
        if (widget.imageUrlCallBack != null) {
          widget.imageUrlCallBack!(widget.imagesUrlList);
        }
        setState(() {});
      }
    }
  }
}
